const fs = require('fs').promises;
const path = require('path');
const { createLogger } = require('./logger');

const logger = createLogger('fileSystem');

// Base paths
const CONFIG_DIR = path.join(__dirname, '../config');
const LOGS_DIR = path.join(__dirname, '../logs');

// Ensure directories exist
async function ensureDirectoryExists(dirPath) {
  try {
    await fs.mkdir(dirPath, { recursive: true });
    logger.debug(`Ensured directory exists: ${dirPath}`);
  } catch (error) {
    logger.error(`Error creating directory ${dirPath}: ${error.message}`);
    throw error;
  }
}

// Read JSON file, create if not exists with default content
async function readJsonFile(filePath, defaultContent = {}) {
  try {
    await ensureDirectoryExists(path.dirname(filePath));
    
    try {
      const data = await fs.readFile(filePath, 'utf8');
      return JSON.parse(data);
    } catch (error) {
      if (error.code === 'ENOENT') {
        // File doesn't exist, create with default content
        await fs.writeFile(filePath, JSON.stringify(defaultContent, null, 2), 'utf8');
        logger.info(`Created new file with default content: ${filePath}`);
        return defaultContent;
      }
      logger.error(`Error reading JSON file ${filePath}: ${error.message}`);
      throw error;
    }
  } catch (error) {
    logger.error(`Error in readJsonFile for ${filePath}: ${error.message}`);
    throw error;
  }
}

// Write JSON file
async function writeJsonFile(filePath, content) {
  try {
    await ensureDirectoryExists(path.dirname(filePath));
    await fs.writeFile(filePath, JSON.stringify(content, null, 2), 'utf8');
    logger.debug(`Wrote JSON file: ${filePath}`);
  } catch (error) {
    logger.error(`Error writing JSON file ${filePath}: ${error.message}`);
    throw error;
  }
}

// List directories in a directory
async function listDirectories(dirPath) {
  try {
    const entries = await fs.readdir(dirPath, { withFileTypes: true });
    return entries
      .filter(entry => entry.isDirectory())
      .map(entry => entry.name);
  } catch (error) {
    logger.error(`Error listing directories in ${dirPath}: ${error.message}`);
    throw error;
  }
}

// Get file stats
async function getFileStats(filePath) {
  try {
    const stats = await fs.stat(filePath);
    return {
      size: stats.size,
      created: stats.birthtime,
      modified: stats.mtime,
      isDirectory: stats.isDirectory(),
      isFile: stats.isFile()
    };
  } catch (error) {
    if (error.code === 'ENOENT') {
      return null; // File doesn't exist
    }
    logger.error(`Error getting file stats for ${filePath}: ${error.message}`);
    throw error;
  }
}

module.exports = {
  CONFIG_DIR,
  LOGS_DIR,
  ensureDirectoryExists,
  readJsonFile,
  writeJsonFile,
  listDirectories,
  getFileStats
}; 